﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
using XChipMatlab;
using XChip_Common;
using SerialPortHelperLib;
using Newtonsoft.Json;
using System.Runtime.InteropServices;
using System.IO;
using System.Drawing.Imaging;
using BinAnalysisHelp;
using XChipTool.Enties;
using System.Configuration;

namespace XChipTool
{
    public partial class XChip_Lite_CADJ_C : DevExpress.XtraEditors.XtraUserControl
    {
        public parameter_exportManager Pe_dal { get; set; }
        private KeyEventArgs keyEnter = new KeyEventArgs(Keys.Enter);//用来手动触发文本框下发配置
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;
        /// <summary>
        /// 默认值 当前值需要去get到成默认值
        /// </summary>
        bool color_enhance_max_man_en = false;
        int mem_color_enhance_max_man_r = 128, mem_color_enhance_max_man_g = 256, mem_color_enhance_max_man_b = 256, mem_color_enhance_max_man_p = 256, Q_K = 7;
        /// <summary>
        /// 图片文件路劲
        /// </summary>
        string cadjPath = $"{Application.StartupPath}\\cadj.bmp"; //设置默认路径
        /// <summary>
        /// 定义图片坐标系
        /// </summary>
        int cadjX=220, cadjY=416, cadjW=100, cadjH =100;
        public SerialPort sPortTemp;
        private DevExpress.Utils.WaitDialogForm WaitBeforeLogin = null;
        private bool isRead = false;
        private bool isWrite = false;

        public delegate void SendSetCadjImgClick(string path, int x,int y,int w,int h);

        public event SendSetCadjImgClick SendSetClick;
        private addressregisterManager aBll;
        private List<addressregister> XChipCadj_c;
        /// <summary>
        /// get_isp_setting
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            isRead = true;
            #region 未在界面中体现的参数赋值
            /*color_enhance_max_man_en
            color_enhance_max_man_r_h
            color_enhance_max_man_r_l
            color_enhance_max_man_g_h
            color_enhance_max_man_g_l
            color_enhance_max_man_b_h
            color_enhance_max_man_b_l
            color_enhance_max_man_p_h
            color_enhance_max_man_p_l
            */
            color_enhance_max_man_en = GetCADJRegister("color_enhance_max_man_en") == 0;
            mem_color_enhance_max_man_r = (int)((GetCADJRegister("color_enhance_max_man_r_h") << 8) + GetCADJRegister("color_enhance_max_man_r_l"));
            mem_color_enhance_max_man_g = (int)((GetCADJRegister("color_enhance_max_man_g_h") << 8) + GetCADJRegister("color_enhance_max_man_g_l"));
            mem_color_enhance_max_man_b = (int)((GetCADJRegister("color_enhance_max_man_b_h") << 8) + GetCADJRegister("color_enhance_max_man_b_l"));
            mem_color_enhance_max_man_p = (int)((GetCADJRegister("color_enhance_max_man_p_h") << 8) + GetCADJRegister("color_enhance_max_man_p_l"));
            Q_K = (int)(GetCADJRegister("Qk"));
            #endregion
            btn_GetMode_Click(null, null);
            isRead = true;
            List<string> NameList = new List<string>();

            for (int i = 0; i < XChipCadj_c.Count; i++)
            {
                if (XChipCadj_c[i].NameType==("maxV_G_h"))
                {

                }
                var type = AppHelper.NameTypeToString(XChipCadj_c[i].NameType);
                if (XChipCadj_c[i].NameType.Contains("D_L"))
                {
                    type = XChipCadj_c[i].NameType;
                }

                //加上单选框的_en
                if (XChipCadj_c[i].ControlType == "1")
                {
                    type = XChipCadj_c[i].NameType;
                }
                var col = Controls_Find(type);
                foreach (var item in col)
                {
                    if (NameList.Exists(c => c == (type)))
                    {
                        continue;
                    }
                    else
                    {

                        if (item is TextEdit)
                        {

                            var nList = XChipCadj_c.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            if (item.Name.ToLower() == type.ToLower())
                            {
                                nList = XChipCadj_c.Where(c => c.NameType.ToLower() == (item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            }
                            if (nList.Count == 0)
                            {
                                nList = XChipCadj_c.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            }
                            if (nList.Count == 1)
                            {
                                var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                                item.Text = BitsHelp.GetBitsToUint(nList[0].Bits, nList[0].Hex, Val).ToString("X");
                            }
                            else
                            {
                                string Val = string.Empty;
                                //这里默认为是有多个寄存器  一个文本框的情况进行处理
                                if (nList.Exists(c => c.NameType.ToLower().Contains("_h")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_h")).Address, 16), sPortTemp).ToString("X2");
                                }
                                if (nList.Exists(c => c.NameType.ToLower().Contains("_m1")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m1")).Address, 16), sPortTemp).ToString("X2");
                                }
                                if (nList.Exists(c => c.NameType.ToLower().Contains("_m0")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m0")).Address, 16), sPortTemp).ToString("X2");
                                }
                               
                          
                                if (nList.Exists(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                }
                                if ("" == Val)
                                {
                                    nList = XChipCadj_c.Where(c => c.NameType.ToLower() == (item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                                    if (nList.Count() == 1)
                                    {
                                        Val += SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                                    }
                                }
                                item.Text = Val;
                            }
                        }
                        else if (item is CheckEdit)
                        {
                            var nList = XChipCadj_c.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                            if (nList.Count == 1)
                            {
                                var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                                (item as CheckEdit).Checked = BitsHelp.GetBitsCheckedToBool(nList[0].Bits, nList[0].Hex, Val) == 0;
                            }
                        }

                        NameList.Add(item.Name);
                    }
                }
                
            }
            isRead = false;
            WaitBefore.Close();


            U_R.Text = PositiveNegativeConversion(Convert.ToUInt32(U_R.Text, 16)).ToString();
            U_G.Text = PositiveNegativeConversion(Convert.ToUInt32(U_G.Text, 16)).ToString();
            U_B.Text = PositiveNegativeConversion(Convert.ToUInt32(U_B.Text, 16)).ToString();
            U_P.Text = PositiveNegativeConversion(Convert.ToUInt32(U_P.Text, 16)).ToString();

            V_R.Text = PositiveNegativeConversion(Convert.ToUInt32(V_R.Text, 16)).ToString();
            V_G.Text = PositiveNegativeConversion(Convert.ToUInt32(V_G.Text, 16)).ToString();
            V_B.Text = PositiveNegativeConversion(Convert.ToUInt32(V_B.Text, 16)).ToString();
            V_P.Text = PositiveNegativeConversion(Convert.ToUInt32(V_P.Text, 16)).ToString();

            width_R.Text = PositiveNegativeConversion(Convert.ToUInt32(width_R.Text, 16), false).ToString();
            width_G.Text = PositiveNegativeConversion(Convert.ToUInt32(width_G.Text, 16), false).ToString();
            width_B.Text = PositiveNegativeConversion(Convert.ToUInt32(width_B.Text, 16), false).ToString();
            width_P.Text = PositiveNegativeConversion(Convert.ToUInt32(width_P.Text, 16), false).ToString();
            isRead = false;

        }

      

        private long GetCADJRegister(string nameType)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
            }
            if (XChipCadj_c.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
            {
                var model = XChipCadj_c.Find(c => c.NameType.ToLower() == nameType.ToLower());
                var Val = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                if (model.ControlType.Contains("1"))
                {
                    return BitsHelp.GetBitsCheckedToBool(model.Bits, model.Hex, Val.ToString("X2"));
                }
                else
                {
                    return BitsHelp.GetBitsToUint(model.Bits, model.Hex, Val.ToString("X2"));
                }
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }
        private void SetCADJRegister(string nameType, ulong add)
        {
            if (isRead) return;
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                //DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }

            if (IsUsbOpen)
            {
                if (null != BinHelp.usbList  && IsUsbOpen)
                {
                    uint pVule = 0x0;
                    var isbool = false;
                    if (IntPtr.Size == 8)
                    {
                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                    else
                    {
                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                    var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                    var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                    BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, XChipHelp.XChipCADJ.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, add.ToString("X"), chang, kuang);
                }
            }
            else if (m_open)
            {

            }
            else
            {
                if (null != BinHelp.lspList && XChipCadj_c.Where(c => c.NameType.ToLower() == nameType.ToLower()).Count() > 0)
                { //编写Bin更新数据
                    var temp = SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                    BinHelp.SetBinUpdateData(ref BinHelp.BinList, XChipHelp.XChipCADJ.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, add.ToString("X"), (uint)temp);
                }
                
            }
            if (XChipCadj_c.Where(c => c.NameType.ToLower() == nameType.ToLower()).Count() > 0)
            {
                SerialSend.WriteRegister(Convert.ToUInt32(XChipCadj_c.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, 16), add, sPortTemp);

            }

        }

        private void SetCADJRegister(addressregister model, ulong add, bool isCheck = true)
        {
            if (isRead) return;
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }

            //SerialSend.WriteRegister(Convert.ToUInt32(model.Address, 16), add, sPortTemp);


           
            if (IsUsbOpen)
            {
                if (null != BinHelp.usbList)
                {
                    uint pVule = 0x0;
                    var isbool = false;
                    if (IntPtr.Size == 8)
                    {
                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                    }
                    else
                    {
                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                    var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                    var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                    BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, model.Address, add.ToString("X"), chang, kuang);
                }
            }
            else if (m_open)
            {

            }
            else
            {
                if (!sPortTemp.IsOpen)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }
               
                if (null != BinHelp.lspList)
                {   //编写Bin更新数据
                    var temp = SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                    BinHelp.SetBinUpdateData(ref BinHelp.BinList, model.Address, add.ToString("X"), (uint)temp);
                }
            }

            SerialSend.WriteRegister(Convert.ToUInt32(model.Address, 16), add, sPortTemp);
        }

        /// <summary>
        /// 发送包含normal或redlight模式的寄存器
        /// </summary>
        /// <param name="dataField">数据表查找name的前缀</param>
        /// <param name="writeVal">要发送的值</param>
        private void SendNormalORRedlightChecked(string dataField, bool isChecked)
        {
            btn_GetMode_Click(null, null);
            if (CADJ_redlight_adj_en.Checked)
            {
                switch (rdogrp_awb_redlight_status.SelectedIndex)
                {
                    case 0:
                        //SetCADJRegister(dataField.Replace("_en","") + "_normal" + "_en", writeVal);
                        if (XChipCadj_c.Exists(c => c.NameType.ToLower() == (dataField.Replace("_en", "") + "_normal" + "_en").ToLower()))
                        {
                            var model = XChipCadj_c.Find(c => c.NameType.ToLower() == (dataField.Replace("_en", "") + "_normal" + "_en").ToLower());
                            var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                            var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), isChecked);
                            SetCADJRegister(model, Val);
                        }
                        break;
                    case 1:
                        //SetCADJRegister(dataField.Replace("_en", "") + "_redlight" + "_en", writeVal);
                        if (XChipCadj_c.Exists(c => c.NameType.ToLower() == (dataField.Replace("_en", "") + "_redlight" + "_en").ToLower()))
                        {
                            var model = XChipCadj_c.Find(c => c.NameType.ToLower() == (dataField.Replace("_en", "") + "_redlight" + "_en").ToLower());
                            var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                            var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), isChecked);
                            SetCADJRegister(model, Val);
                        }
                        break;
                    default:
                        break;
                }
            }
            else
            {
                //SetCADJRegister(dataField.Replace("_en", "") + "_normal" + "_en", writeVal);
                if (XChipCadj_c.Exists(c => c.NameType.ToLower() == (dataField.Replace("_en", "") + "_normal" + "_en").ToLower()))
                {
                    var model = XChipCadj_c.Find(c => c.NameType.ToLower() == (dataField.Replace("_en", "") + "_normal" + "_en").ToLower());
                    var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), isChecked);
                    SetCADJRegister(model, Val);
                }
            }
            if (XChipCadj_c.Exists(c => c.NameType.ToLower() == (dataField).ToLower()))
            {
                var model = XChipCadj_c.Find(c => c.NameType.ToLower() == (dataField).ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), isChecked);
                SetCADJRegister(model, Val);
            }
            //SetCADJRegister(dataField, writeVal);
        }

        #region 勾选框改变逻辑
        private void chk_CADJ_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            
            if (XChipCadj_c.Exists(c => c.NameType.ToLower() == chk.Name.ToLower()))
            {
                var model = XChipCadj_c.Find(c => c.NameType.ToLower() == chk.Name.ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
                SetCADJRegister(model, Val);
            }
        }
        /// <summary>
        /// 发送包含normal或redlight模式的寄存器
        /// </summary>
        /// <param name="dataField">数据表查找name的前缀</param>
        /// <param name="writeVal">要发送的值</param>
        private void SendNormalORRedlight(string dataField, uint writeVal)
        {
            btn_GetMode_Click(null, null);
            if (CADJ_redlight_adj_en.Checked)
            {
                switch (rdogrp_awb_redlight_status.SelectedIndex)
                {
                    case 0:
                        SetCADJRegister(dataField + "_normal", writeVal);
                        break;
                    case 1:
                        SetCADJRegister(dataField + "_redlight", writeVal);
                        break;
                    default:
                        break;
                }
            }
            else
            {
                SetCADJRegister(dataField + "_normal", writeVal);
            }
            SetCADJRegister(dataField, writeVal);
        }
        #region color_enhance 系列勾选框逻辑
        private void mem_color_enhance_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            #region 界面逻辑
            if (chk.Checked)
            {
                //chroma_suppress_en.Checked = false;

                Red_enh_en.Enabled = true;
                Green_enh_en.Enabled = true;
                Blue_enh_en.Enabled = true;
                Purple_enh_en.Enabled = true;
            }
            else
            {
                Red_enh_en.Enabled = false;
                Green_enh_en.Enabled = false;
                Blue_enh_en.Enabled = false;
                Purple_enh_en.Enabled = false;
            }
            #endregion
            #region 下发逻辑
            if (!isRead)
            {
                string dataField = chk.Name.ToString();
                //var readVal = GetCADJRegister(dataField);
                //var writeVal = chk.Checked ? (uint)readVal | 0x10 : (uint)readVal & 0xef;
                SendNormalORRedlightChecked(dataField, chk.Checked);
            }
            #endregion
        }
      

        private void mem_color_enhance_r_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            #region 界面逻辑
            if (chk.Checked)
            {
                Red_sup_en.Checked = false;
            }
            else
            {

            }
            #endregion
            #region 下发逻辑
            if (!isRead)
            {
                string dataField = chk.Name.ToString();
                //var readVal = GetCADJRegister(dataField);
                //var writeVal = chk.Checked ? (uint)readVal | 0x08 : (uint)readVal & 0xf7;
                SendNormalORRedlightChecked(dataField, chk.Checked);
            }
            #endregion
        }
        private void mem_color_enhance_g_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            #region 下发逻辑
            if (!isRead)
            {
                string dataField = chk.Name.ToString();
                //var readVal = GetCADJRegister(dataField);
                //var writeVal = chk.Checked ? (uint)readVal | 0x04 : (uint)readVal & 0xfb;
                SendNormalORRedlightChecked(dataField, chk.Checked);
            }
            #endregion
        }

        private void mem_color_enhance_b_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            #region 下发逻辑
            if (!isRead)
            {
                string dataField = chk.Name.ToString();
                //var readVal = GetCADJRegister(dataField);
                //var writeVal = chk.Checked ? (uint)readVal | 0x02 : (uint)readVal & 0xfd;
                SendNormalORRedlightChecked(dataField, chk.Checked);
            }
            #endregion
        }
        private void mem_color_enhance_p_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            #region 界面逻辑
            if (chk.Checked)
            {
                Red_sup_en.Checked = false;
            }
            else
            {

            }
            #endregion
            #region 下发逻辑
            if (!isRead)
            {
                string dataField = chk.Name.ToString();
                //var readVal = GetCADJRegister(dataField);
                //var writeVal = chk.Checked ? (uint)readVal | 0x01 : (uint)readVal & 0xfe;
                SendNormalORRedlightChecked(dataField, chk.Checked);
            }
            #endregion
        }
        #endregion
        #region chroma suppress 系列勾选框逻辑
        private void chroma_suppress_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            #region 界面逻辑
            if (chk.Checked)
            {
                //mem_color_enhance_max_man_en.Checked = false;

                Luma_sup_en.Enabled = true;
                Sat_sup_en.Enabled = true;
                Red_sup_en.Enabled = true;
            }
            else
            {
                Luma_sup_en.Enabled = false;
                Sat_sup_en.Enabled = false;
                Red_sup_en.Enabled = false;
            }
            #endregion
            #region 下发逻辑
            if (!isRead)
            {
                string dataField = chk.Name.ToString();
                //var readVal = GetCADJRegister(dataField);
                //var writeVal = chk.Checked ? (uint)readVal | 0x08 : (uint)readVal & 0xf7;
                SendNormalORRedlightChecked(dataField, chk.Checked);
            }
            #endregion          
        }
        private void chroma_suppress_l_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            #region 下发逻辑
            if (!isRead)
            {
                string dataField = chk.Name.ToString();
                //var readVal = GetCADJRegister(dataField);
                //var writeVal = chk.Checked ? (uint)readVal | 0x04 : (uint)readVal & 0xfb;
                SendNormalORRedlightChecked(dataField, chk.Checked);
            }
            #endregion          
        }

        private void chroma_suppress_s_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            #region 下发逻辑
            if (!isRead)
            {
                string dataField = chk.Name.ToString();
                //var readVal = GetCADJRegister(dataField);
                //var writeVal = chk.Checked ? (uint)readVal | 0x02 : (uint)readVal & 0xfd;
                SendNormalORRedlightChecked(dataField, chk.Checked);
            }
            #endregion              
        }
        private void chroma_suppress_r_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            if (chk.Checked)
            {
                Red_enh_en.Checked = false;
                Purple_enh_en.Checked = false;
            }
            else
            {

            }
            #region 下发逻辑
            if (!isRead)
            {
                string dataField = chk.Name.ToString();
                //var readVal = GetCADJRegister(dataField);
                //var writeVal = chk.Checked ? (uint)readVal | 0x01 : (uint)readVal & 0xfe;
                SendNormalORRedlightChecked(dataField, chk.Checked);
            }
            #endregion          
        }
        #endregion
        private void scale_enhance_man_en_CheckedChanged(object sender, EventArgs e)
        {

            var chk = sender as CheckEdit;
            #region 界面逻辑
            SetScale_enh_Enable(chk.Checked);
            #endregion
            #region 下发逻辑
            if (!isRead)
            {
                string dataField = chk.Name.ToString();
                var readVal = GetCADJRegister(dataField);
                var writeVal = chk.Checked ? (uint)readVal | 0x01 : (uint)readVal & 0xfe;
                SetCADJRegister(dataField, writeVal);
            }
            #endregion
        }

        private void scale_suppress_man_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            SetScale_sup_Enable(chk.Checked);
            #region 下发逻辑
            if (!isRead)
            {
                string dataField = chk.Name.ToString();
                //var readVal = GetCADJRegister(dataField);
                //var writeVal = chk.Checked ? (uint)readVal | 0x01 : (uint)readVal & 0xfe;
                SendNormalORRedlightChecked(dataField, chk.Checked);
            }
            #endregion
        }
        #region mode selection 勾选框
        private void cadj_redlight_adj_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            #region 界面逻辑
            chk_Debug.Enabled = chk.Checked;
            #endregion
            #region 下发逻辑
            if (!isRead)
            {
                string dataField = chk.Name.ToString();
                var readVal = GetCADJRegister(dataField);
                var writeVal = chk.Checked ? (uint)readVal | 0x01 : (uint)readVal & 0xfe;
                SetCADJRegister(dataField, writeVal);
            }
            #endregion
        }
        private void chk_Debug_EnabledChanged(object sender, EventArgs e)
        {
            if (!chk_Debug.Enabled)
                chk_Debug.Checked = false;
        }
        private void chk_Debug_CheckedChanged(object sender, EventArgs e)
        {
            rdogrp_awb_redlight_status.Enabled = chk_Debug.Checked;
        }
        private void rdogrp_awb_redlight_status_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!isRead)
            {
                if (rdogrp_awb_redlight_status.SelectedIndex == 0)
                {//Normal
                    SetCADJRegister(rdogrp_awb_redlight_status.Name.ToString(), 0x00);
                }
                else if (rdogrp_awb_redlight_status.SelectedIndex == 1)
                {//Redlight
                    SetCADJRegister(rdogrp_awb_redlight_status.Name.ToString(), 0x01);
                }
            }           
        }
        #endregion
        private void SetScale_enh_Enable(bool isbool)
        {
            scale_enh_manual.Enabled = isbool;
            scale_enh_1x.Enabled = !isbool;
            scale_enh_2x.Enabled = !isbool;
            scale_enh_4x.Enabled = !isbool;
            scale_enh_8x.Enabled = !isbool;
            scale_enh_16x.Enabled = !isbool;
            scale_enh_32x.Enabled = !isbool;
            scale_enh_64x.Enabled = !isbool;
            scale_enh_128x.Enabled = !isbool;
            scale_enh_256x.Enabled = !isbool;
        }

        private void SetScale_sup_Enable(bool isbool)
        {
            scale_sup_manual.Enabled = isbool;
            scale_sup_1x.Enabled = !isbool;
            scale_sup_2x.Enabled = !isbool;
            scale_sup_4x.Enabled = !isbool;
            scale_sup_8x.Enabled = !isbool;
            scale_sup_16x.Enabled = !isbool;
            scale_sup_32x.Enabled = !isbool;
            scale_sup_64x.Enabled = !isbool;
            scale_sup_128x.Enabled = !isbool;
            scale_sup_256x.Enabled = !isbool;
        }
        #endregion
        /// <summary>
        /// color zone send 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton6_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            //if (!JudgeCadjTxt()) return;
            PackedColorZone( simpleButton6);
        }
        /// <summary>
        /// color enhance send
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            if (!JudgeCadjTxt()) return;
            PackedColorEnhance(btn_Refresh);
        }
        /// <summary>
        /// chroma suppress send
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton7_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            if (!JudgeCadjTxt()) return;
            PackedChromaSuppress(simpleButton7);
        }
       

        private void btn_TuningTips_Click(object sender, EventArgs e)
        {
            //string str = "\t      \t Color zone模块设定值用于在UV坐标系中框选出需增强的红色、绿色、蓝色、紫色区域，4种颜色以原点为坐标（0，0），各自色相区域为正向坐标值，如示意图；通过color_image可加载一张色彩图，点“Send”后框选出需增强颜色，可查看框选区域在坐标系中的分布。\r\n"
            //    + "\t      \t Color enhance模块设定值用于调节框选的4种颜色在亮度通道中的增益值，maxV为最大强度增益值，Y1、Y2、Y3、Y4为像素Y阈值。\r\n"
            //    + "\t      \t Chroma suppress模块中D_L、D_S、D_R分别设定亮度通道、饱和度通道、单独红色抑制的最大抑制程度，0x80 为无抑制效果，0x00 为最强抑制效果；Y1、Y2、Y3、Y4为亮度通道中的横坐标Y阈值，Max_F固定为0x80；S1、S2为饱和度通道中的横坐标Sat阈值。\r\n"
            //    + "\t      \t Scale_enh调节不同增益下的增强倍率，值越大，增强越强；scale_sup调节不同增益下的抑制倍率，值越大，抑制越强。\r\n"
            //    + "\t      \t 注意：UV坐标系中框选的两两区域不能重叠；红色抑制和红色增强不能同时使能；红色抑制和紫色增强不建议同时使能。\r\n";
            string str = "";
            XChip_OptimizationTips ot = new XChip_OptimizationTips("CADJ调优Tips", str);
            ot.StartPosition = FormStartPosition.CenterScreen;
            //ot.ShowDialog();
            ot.Show();
        }

        private void btn_SaveISPSetting_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }

            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "配置文件（*.txt）|*.txt";

            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "IQ_Setting_CADJ_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                SerialSend.isDebug = false;
                StringBuilder sb = new StringBuilder();
                Pe_dal = new parameter_exportManager();
                if (null != Pe_dal)
                {
                    WaitBefore.Start("参数导出", "正在加载中", 60);
                    //var tempList = Pe_dal.GetList().OrderBy(c => c.SortNum);
                    var tempList = Pe_dal.GetListToExport("ALL").Where(c => c.PidM == "CADJ"||c.Module == "chroma_adjust").OrderBy(c => c.SortNum).ToList();
                    #region 判断是否需要用白天的数据
                    var Pe_patch_dal = new parameter_export_patchManager();
                    var patchList = Pe_patch_dal.GetList();
                    var conditionList = tempList.Select(c => c.ConditionAddr).Distinct().ToList();
                    foreach (var item in conditionList)
                    {
                        if (SerialSend.ReadRegister(Convert.ToUInt32(item, 16), sPortTemp) == 0)
                        {
                            patchList.RemoveAll(c => c.ConditionAddr == item);
                        }
                    }
                    #endregion
                    sb.Append("0xfffd, 0x80,\n");
                    sb.Append($"//{tempList.First().Module}\n");
                    foreach (var item in tempList)
                    {
                        try
                        {
                            sb.Append(string.IsNullOrEmpty(item.PreNote) ? "" : "\n" + item.PreNote + "\n");
                            sb.Append(string.IsNullOrEmpty(item.addr) ? "" : item.addr);
                            #region 判断是否需要用白天的数据
                            if (!string.IsNullOrEmpty(item.ReadAddr))
                            {
                                if (patchList.Count != 0 && patchList.Select(c => c.ReadAddr).Contains(item.ReadAddr))
                                {
                                    sb.Append($",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.RelationAddr.Trim(), 16)), sPortTemp).ToString("x2")},");
                                }
                                else
                                {
                                    sb.Append($",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.ReadAddr.Trim(), 16)), sPortTemp).ToString("x2")},");
                                }
                            }
                            #endregion
                            sb.Append(string.IsNullOrEmpty(item.RearNote) ? "" : item.RearNote = item.RearNote.Replace("\\n", "\n").Replace("\\r", "\r"));
                            sb.Append("\n");
                        }
                        catch (Exception ex)
                        {
                            WaitBefore.Close();
                            //setShowMsg(item.RelationAddr);
                            DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                            return;
                        }
                    }
                    System.IO.File.WriteAllText(sfd.FileName, sb.ToString());
                    WaitBefore.Close();
                    DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
                }
            }
            SerialSend.isDebug = true;
        }

        private void btn_GetMode_Click(object sender, EventArgs e)
        {
            isRead = true;
            CADJ_redlight_adj_en.Checked = GetCADJRegister(CADJ_redlight_adj_en.Tag.ToString()) == 0x01;
            switch (GetCADJRegister(rdogrp_awb_redlight_status.Tag.ToString()))
            {
                case 0x00://Normal
                    rdogrp_awb_redlight_status.SelectedIndex = 0;
                    break;
                case 0x01://Redlight
                    rdogrp_awb_redlight_status.SelectedIndex = 1;
                    break;
                default:
                    break;
            }
            isRead = false;
        }

        private void scale_enhance_man_KeyDown(object sender, KeyEventArgs e)
        {
            var txt = sender as TextEdit;
            if(e.KeyCode == Keys.Enter)
            {
                SetCADJRegister(txt.Name.ToString(), Convert.ToUInt32(txt.Text, 16));
            }
        }

        private void scale_enhance_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_enhance_man_KeyDown(sender, keyEnter);
        }

        private void scale_suppress_man_KeyDown(object sender, KeyEventArgs e)
        {
            var txt = sender as TextEdit;
            if (e.KeyCode == Keys.Enter)
            {
                SendNormalORRedlight(txt.Name.ToString(), Convert.ToUInt32(txt.Text, 16));
            }
        }

        private void scale_suppress_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_suppress_man_KeyDown(sender, keyEnter);
        }

        private void txt_scale_enh_KeyDown(object sender, KeyEventArgs e)
        {
            var txt = sender as TextEdit;
            if (e.KeyCode == Keys.Enter)
            {
                SetCADJRegister(txt.Name.ToString(), Convert.ToUInt32(txt.Text, 16));
            }
        }

        private void txt_scale_enh_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_scale_enh_KeyDown(sender, keyEnter);
        }

        private void txt_scale_sup_KeyDown(object sender, KeyEventArgs e)
        {
            var txt = sender as TextEdit;
            if (e.KeyCode == Keys.Enter)
            {
                SetCADJRegister(txt.Name.ToString(), Convert.ToUInt32(txt.Text, 16));
            }
        }

        private void txt_scale_sup_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_scale_sup_KeyDown(sender, keyEnter);
        }

        private void K_r_EditValueChanged(object sender, EventArgs e)
        {
            var ks = sender as TextEdit;
            if (!string.IsNullOrEmpty(ks.Text)&&Convert.ToInt32(ks.Text, 16)>Convert.ToInt32("1FF",16))
            {
                ks.Text = "1FF";
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void XChip_CADJ_Load(object sender, EventArgs e)
        {
            U_R.Text = string.Empty;
            V_R.Text = string.Empty;
            U_G.Text = string.Empty;
            V_G.Text = string.Empty;
            U_B.Text = string.Empty;
            V_B.Text = string.Empty;
            U_P.Text = string.Empty;
            V_P.Text = string.Empty;
            maxV_R.Text = string.Empty;
            maxV_G.Text = string.Empty;
            maxV_B.Text = string.Empty;
            maxV_P.Text = string.Empty;
            y1_R.Text = string.Empty;
            y2_R.Text = string.Empty;
            y3_R.Text = string.Empty;
            y4_R.Text = string.Empty;
            y1_G.Text = string.Empty;
            y2_G.Text = string.Empty;
            y3_G.Text = string.Empty;
            y4_G.Text = string.Empty;
            y1_B.Text = string.Empty;
            y2_B.Text = string.Empty;
            y3_B.Text = string.Empty;
            y4_B.Text = string.Empty;
            y1_P.Text = string.Empty;
            y2_P.Text = string.Empty;
            y3_P.Text = string.Empty;
            y4_P.Text = string.Empty;
            width_R.Text = string.Empty;
            width_G.Text = string.Empty;
            width_B.Text = string.Empty;
            width_P.Text = string.Empty;
            D_L.Text = string.Empty;
            D_S.Text = string.Empty;
            D_R.Text = string.Empty;
            y1.Text = string.Empty;
            y2.Text = string.Empty;
            y3.Text = string.Empty;
            y4.Text = string.Empty;
            s1.Text = string.Empty;
            s2.Text = string.Empty;
            scale_sup_manual.Text = string.Empty;
            scale_enh_manual.Text = string.Empty;
        }

        bool JudgeCadjTxt()
        {
            //if (mem_color_enhance_max_man_en.Checked)
            //{
                //if (mem_color_enhance_max_man_r > int.Parse(width_R.Text))
                //{
                //    DevExpress.XtraEditors.XtraMessageBox.Show($"mem_color_enhance_max_man_r值是{mem_color_enhance_max_man_r} 大于 MaxV Red  参数错误！");
                //    return false;
                //}
                //if (mem_color_enhance_max_man_g > int.Parse(width_G.Text))
                //{
                //    DevExpress.XtraEditors.XtraMessageBox.Show($"mem_color_enhance_max_man_g值是{mem_color_enhance_max_man_g} 大于 MaxV Green  参数错误！");
                //    return false;
                //}
                //if (mem_color_enhance_max_man_b > int.Parse(width_B.Text))
                //{
                //    DevExpress.XtraEditors.XtraMessageBox.Show($"mem_color_enhance_max_man_b值是{mem_color_enhance_max_man_b} 大于 MaxV Blue  参数错误！");
                //    return false;
                //}
                //if (mem_color_enhance_max_man_p > int.Parse(width_P.Text))
                //{
                //    DevExpress.XtraEditors.XtraMessageBox.Show($"mem_color_enhance_max_man_p值是{mem_color_enhance_max_man_p} 大于 MaxV Purple  参数错误！");
                //    return false;
                //}
            //}

            if ((CADJ_en.Checked == true && chroma_suppress_en.Checked == false) && (Red_enh_en.Checked == true && Green_enh_en.Checked == true) ||
                (CADJ_en.Checked == true && chroma_suppress_en.Checked == false) && (Red_sup_en.Checked == true && Green_enh_en.Checked == true))
            {
                if ((Math.Abs(int.Parse(V_R.Text)) + Math.Abs(int.Parse(V_G.Text))) <= (int.Parse(width_R.Text) + int.Parse(width_G.Text)))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("在CADJ_en && Red_enh_enn开启时或者在CADJ_en && red_sup_en 时 Red V +  Green V  小于等于 Red Width + Green Width ！");
                    return false;
                }
            }

            if (CADJ_en.Checked && Green_enh_en.Checked && Blue_enh_en.Checked)
            {
                if ((Math.Abs(int.Parse(U_G.Text)) + Math.Abs(int.Parse(U_B.Text))) <= (int.Parse(width_G.Text) + int.Parse(width_B.Text)))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("在CADJ_en && Green_enh_en && Blue_enh_en开启时  Green U + Blue U 小于等于 Green Width + Blue Width ！");
                    return false;
                }
            }


            if (CADJ_en.Checked && Blue_enh_en.Checked && Purple_enh_en.Checked)
            {
                if ((Math.Abs(int.Parse(U_B.Text)) + Math.Abs(int.Parse(U_P.Text))) <= (int.Parse(width_B.Text) + int.Parse(width_P.Text)))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("在CADJ_en && Blue_enh_en && Purple_enh_en 开启时 Blue U + Purple  U  小于等于 Blue Width + Purple Width ！");
                    return false;
                }
            }


            if ((CADJ_en.Checked == true && chroma_suppress_en.Checked == false) && (Red_enh_en.Checked == true && Purple_enh_en.Checked == true) ||
                (CADJ_en.Checked == true && chroma_suppress_en.Checked == false) && (Red_sup_en.Checked == true && Purple_enh_en.Checked == true))
            {
                if ((Math.Abs(int.Parse(U_R.Text)) + Math.Abs(int.Parse(U_P.Text))) <= (int.Parse(width_R.Text) + int.Parse(width_P.Text)))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("在CADJ_en && Red_enh_enn开启 或者 在CADJ_en && red_sup_en开启时 Red U + Purple U  小于等于 Red Width + Purple Width ！");
                    return false;
                }
            }



            if (string.IsNullOrEmpty(scale_enh_manual.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("scale_enh_manual 参数缺省！");
                return false;
            }
            if (string.IsNullOrEmpty(scale_sup_manual.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("scale_sup_manual 参数缺省！");
                return false;
            }

            //boundary 数据判断
            if (string.IsNullOrEmpty(U_R.Text) ||
                string.IsNullOrEmpty(V_R.Text) ||
                string.IsNullOrEmpty(U_G.Text) ||
                string.IsNullOrEmpty(V_G.Text) ||
                string.IsNullOrEmpty(U_B.Text) ||
                string.IsNullOrEmpty(V_B.Text) ||
                string.IsNullOrEmpty(U_P.Text) ||
                string.IsNullOrEmpty(V_P.Text)
                )
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("color zone U或V 参数缺省！");
                return false;
            }


            if (string.IsNullOrEmpty(maxV_R.Text) ||
               string.IsNullOrEmpty(maxV_G.Text) ||
               string.IsNullOrEmpty(maxV_B.Text) ||
               string.IsNullOrEmpty(maxV_P.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("color enhance MaxV 参数缺省！");
                return false;
            }
            if (string.IsNullOrEmpty(y1_R.Text) ||
                string.IsNullOrEmpty(y2_R.Text) ||
                string.IsNullOrEmpty(y3_R.Text) ||
                string.IsNullOrEmpty(y4_R.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("color enhance Y Red 参数缺省！");
                return false;
            }
            if (string.IsNullOrEmpty(y1_G.Text) ||
                string.IsNullOrEmpty(y2_G.Text) ||
                string.IsNullOrEmpty(y3_G.Text) ||
                string.IsNullOrEmpty(y4_G.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("color enhance Y Green 参数缺省！");
                return false;
            }
            if (string.IsNullOrEmpty(y1_B.Text) ||
                string.IsNullOrEmpty(y2_B.Text) ||
                string.IsNullOrEmpty(y3_B.Text) ||
                string.IsNullOrEmpty(y4_B.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("color enhance Y Blue 参数缺省！");
                return false;
            }
            if (string.IsNullOrEmpty(y1_P.Text) ||
                string.IsNullOrEmpty(y2_P.Text) ||
                string.IsNullOrEmpty(y3_P.Text) ||
                string.IsNullOrEmpty(y4_P.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("color enhance Y Purple 参数缺省！");
                return false;
            }
            if (string.IsNullOrEmpty(width_R.Text) ||
                string.IsNullOrEmpty(width_G.Text) ||
                string.IsNullOrEmpty(width_B.Text) ||
                string.IsNullOrEmpty(width_P.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("color zone Width 参数缺省！");
                return false;
            }
            if (Convert.ToInt32(width_R.Text, 10) < 16 || Convert.ToInt32(width_R.Text, 10) >= 32)
            {
                //DevExpress.XtraEditors.XtraMessageBox.Show("color zone width_R 参数范围在0x10-0x20");
                DevExpress.XtraEditors.XtraMessageBox.Show("16 <= Red Width < 32 ");
                width_R.Text = string.Empty;
                return false;
            }
            if (Convert.ToInt32(width_G.Text, 10) < 16 || Convert.ToInt32(width_G.Text, 10) >= 32)
            {
                //DevExpress.XtraEditors.XtraMessageBox.Show("color zone width_G 参数范围在0x10-0x20");
                DevExpress.XtraEditors.XtraMessageBox.Show("16 <= Green Width < 32 ");
                width_G.Text = string.Empty;
                return false;
            }
            if (Convert.ToInt32(width_B.Text, 10) < 16 || Convert.ToInt32(width_B.Text, 10) >= 32)
            {
                //DevExpress.XtraEditors.XtraMessageBox.Show("color zone width_B 参数范围在0x10-0x20");
                DevExpress.XtraEditors.XtraMessageBox.Show("16 <= Blue Width < 32 ");
                width_B.Text = string.Empty;
                return false;
            }
            if (Convert.ToInt32(width_P.Text, 10) < 16 || Convert.ToInt32(width_P.Text, 10) >= 32)
            {
                //DevExpress.XtraEditors.XtraMessageBox.Show("color zone width_P 参数范围在0x10-0x20");
                DevExpress.XtraEditors.XtraMessageBox.Show("16 <= Purple Width < 32 ");
                width_P.Text = string.Empty;
                return false;
            }
            if (string.IsNullOrEmpty(D_L.Text) ||
                string.IsNullOrEmpty(D_S.Text) ||
                string.IsNullOrEmpty(D_R.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("chroma suppress D 参数缺省！");
                return false;
            }

            if (Convert.ToInt32(D_L.Text, 16) < 0 || Convert.ToInt32(D_L.Text, 16) >= 128)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(" 0x00 <= D_L < 0x80");
                D_L.Text = string.Empty;
                return false;
            }
            if (Convert.ToInt32(D_S.Text, 16) < 0 || Convert.ToInt32(D_S.Text, 16) >= 128)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("0x00 <= D_S < 0x80");
                D_S.Text = string.Empty;
                return false;
            }
            if (Convert.ToInt32(D_R.Text, 16) < 0 || Convert.ToInt32(D_R.Text, 16) >= 128)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("0x00 <= D_R < 0x80");
                D_R.Text = string.Empty;
                return false;
            }
            if (string.IsNullOrEmpty(y1.Text) ||
               string.IsNullOrEmpty(y2.Text) ||
               string.IsNullOrEmpty(y3.Text) ||
               string.IsNullOrEmpty(y4.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("chroma suppress Y 参数缺省！");
                return false;
            }
            if (string.IsNullOrEmpty(s1.Text) ||
              string.IsNullOrEmpty(s2.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("chroma suppress S 参数缺省！");
                return false;
            }

            //新增
            if (CADJ_en.Checked && Blue_enh_en.Checked && Purple_enh_en.Checked)
            {
                if ((Math.Abs(int.Parse(V_B.Text)) + Math.Abs(int.Parse(V_P.Text))) < (int.Parse(width_B.Text) + int.Parse(width_P.Text)))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("Blue V + Purple  V  小于 Blue Width + Purple Width ！");
                    return false;
                }
            }
            //chrome suppress下
            if (Math.Abs(Convert.ToInt32(y1.Text, 16) - Convert.ToInt32(y2.Text, 16)) < 16 || Math.Abs(Convert.ToInt32(y1.Text, 16) - Convert.ToInt32(y2.Text, 16)) > 127)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y1与Y2的相差值必须大于等于0x10且小于0x80");
                return false;
            }
            if (Math.Abs(Convert.ToInt32(y3.Text, 16) - Convert.ToInt32(y4.Text, 16)) < 16 || Math.Abs(Convert.ToInt32(y3.Text, 16) - Convert.ToInt32(y4.Text, 16)) > 127)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y3与Y4的相差值必须大于等于0x10且小于0x80");
                return false;
            }
            if (Math.Abs(Convert.ToInt32(s1.Text, 16) - Convert.ToInt32(s2.Text, 16)) < 16 || Math.Abs(Convert.ToInt32(s1.Text, 16) - Convert.ToInt32(s2.Text, 16)) > 127)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("S1与S2的相差值必须大于等于0x10且小于0x80");
                return false;
            }
            if (Convert.ToInt32(s1.Text, 16) > Convert.ToInt32(s2.Text, 16))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("S1必须小于S2");
                return false;
            }
            if (Convert.ToInt32(y1.Text, 16) > Convert.ToInt32(y2.Text, 16))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y1必须小于Y2");
                return false;
            }
            if (Convert.ToInt32(y3.Text, 16) > Convert.ToInt32(y4.Text, 16))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y3必须小于Y4");
                return false;
            }
            //color enhance下
            //y1_R-y2_R
            if (Math.Abs(Convert.ToInt32(y1_R.Text, 16) - Convert.ToInt32(y2_R.Text, 16)) > 128)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y1_Red与Y2_Red的相差值必须小于等于0x80");
                return false;
            }
            if (Convert.ToInt32(y2_R.Text, 16) - Convert.ToInt32(y1_R.Text, 16) < 16 || Convert.ToInt32(y2_R.Text, 16) - Convert.ToInt32(y1_R.Text, 16) > 127)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y2_Red - Y1_Red的值必须大于等于0x10且小于0x80");
                return false;
            }

            //y3_R-y4_R
            if (Math.Abs(Convert.ToInt32(y3_R.Text, 16) - Convert.ToInt32(y4_R.Text, 16)) > 128)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y3_Red与Y4_Red的相差值必须小于等于0x80");
                return false;
            }
            if (Convert.ToInt32(y4_R.Text, 16) - Convert.ToInt32(y3_R.Text, 16) < 16 || Convert.ToInt32(y4_R.Text, 16) - Convert.ToInt32(y3_R.Text, 16) > 127)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y4_Red - Y3_Red的值必须大于等于16且小于0x80");
                return false;
            }
            //y1_G-y2_G
            if (Math.Abs(Convert.ToInt32(y1_G.Text, 16) - Convert.ToInt32(y2_G.Text, 16)) > 128)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y1_Green与Y2_Green的相差值必须小于等于0x80");
                return false;
            }
            if (Convert.ToInt32(y2_G.Text, 16) - Convert.ToInt32(y1_G.Text, 16) < 16 || Convert.ToInt32(y2_G.Text, 16) - Convert.ToInt32(y1_G.Text, 16) > 127)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y2_Green - Y1_Green的值必须大于等于0x10且小于0x80");
                return false;
            }
            //y3_G-y4_G
            if (Math.Abs(Convert.ToInt32(y3_G.Text, 16) - Convert.ToInt32(y4_G.Text, 16)) > 128)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y3_Green与Y4_Green的相差值必须小于等于0x80");
                return false;
            }
            if (Convert.ToInt32(y4_G.Text, 16) - Convert.ToInt32(y3_G.Text, 16) < 16 || Convert.ToInt32(y4_G.Text, 16) - Convert.ToInt32(y3_G.Text, 16) > 127)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y4_Green - Y3_Green的值必须大于等于0x10且小于0x80");
                return false;
            }
            //y1_B-y2_B
            if (Math.Abs(Convert.ToInt32(y1_B.Text, 16) - Convert.ToInt32(y2_B.Text, 16)) > 128)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y1_Blue与Y2_Blue的相差值必须小于等于0x80");
                return false;
            }
            if (Convert.ToInt32(y2_B.Text, 16) - Convert.ToInt32(y1_B.Text, 16) < 16 || Convert.ToInt32(y2_B.Text, 16) - Convert.ToInt32(y1_B.Text, 16) > 127)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y2_Blue - Y1_Blue的值必须大于等于0x10且小于0x80");
                return false;
            }
            //y3_B-y4_B
            if (Math.Abs(Convert.ToInt32(y3_B.Text, 16) - Convert.ToInt32(y4_B.Text, 16)) > 128)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y3_Blue与Y4_Blue的相差值必须小于等于0x80");
                return false;
            }
            if (Convert.ToInt32(y4_B.Text, 16) - Convert.ToInt32(y3_B.Text, 16) < 16 || Convert.ToInt32(y4_B.Text, 16) - Convert.ToInt32(y3_B.Text, 16) > 127)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y4_Blue - Y3_Blue的值必须大于等于0x10且小于0x80");
                return false;
            }
            //y1_P-y2_P
            if (Math.Abs(Convert.ToInt32(y1_P.Text, 16) - Convert.ToInt32(y2_P.Text, 16)) > 128)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y1_Purple与Y2_Purple的相差值必须小于等于0x80");
                return false;
            }
            if (Convert.ToInt32(y2_P.Text, 16) - Convert.ToInt32(y1_P.Text, 16) < 16 || Convert.ToInt32(y2_P.Text, 16) - Convert.ToInt32(y1_P.Text, 16) > 127)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y2_Purple - Y1_Purple的值必须大于等于0x10且小于0x80");
                return false;
            }
            //y3_P-y4_P
            if (Math.Abs(Convert.ToInt32(y3_P.Text, 16) - Convert.ToInt32(y4_P.Text, 16)) > 128)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y3_Purple与Y4_Purple的相差值必须小于等于0x80");
                return false;
            }
            if (Convert.ToInt32(y4_P.Text, 16) - Convert.ToInt32(y3_P.Text, 16) < 16 || Convert.ToInt32(y4_P.Text, 16) - Convert.ToInt32(y3_P.Text, 16) > 127)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Y4_Purple - Y3_Purple的值必须大于等于0x10且小于0x80");
                return false;
            }
            return true;
        }

        int unAbs(int a)
        {

            return (a > 0) ? -a :Math.Abs(a);
        }
        void PackedColorZone( SimpleButton btn) {
            btn.Invoke((EventHandler)delegate { btn.Enabled = false; });
            var readpath = cadjPath;
            //readpath = $"{Application.StartupPath}\\00.bmp";
            var savepath = string.Format("{0}\\Lib\\xc_m\\{1}", Application.StartupPath, $"Cadj_Out{DateTime.Now.ToString("ddHHmmss")}{System.IO.Path.GetFileNameWithoutExtension(cadjPath)}.bmp");
            var strpath = string.Format("{0}\\Lib\\xc_m\\{1}", Application.StartupPath, $"ColorZone_Out{DateTime.Now.ToString("ddHHmmss")}{System.IO.Path.GetFileNameWithoutExtension(cadjPath)}.txt");
            //设置坐标点
            //var irow = new double[4, 2] { { cadjX, cadjY }, { cadjX + cadjW, cadjY }, { cadjX + cadjW, cadjY + cadjH }, { cadjX, cadjY + cadjH } };
            var irow = new double[4, 2] { { cadjY, cadjX }, { cadjY, cadjX + cadjW }, { cadjY + cadjH, cadjX + cadjW }, { cadjY + cadjH, cadjX } };
            //if (null== SendSetClick)
            //{
            //    SendSetClick(cadjPath, cadjX, cadjY, cadjW, cadjH);
            //}
            //var t=  new double[4, 2] { {220,412 }, { 332,412}, {332,524 }, { 220,524} };
            //boundary 坐标系
            var boundary = new double[4, 2] { { int.Parse(U_R.Text),int.Parse(V_R.Text) },
                { int.Parse(U_G.Text),int.Parse(V_G.Text) },
                {int.Parse(U_B.Text),int.Parse(V_B.Text) },
                { int.Parse(U_P.Text),int.Parse(V_P.Text) }
            };


            var paraWidth = new double[] {
                Convert.ToInt32(width_R.Text),
                Convert.ToInt32(width_G.Text),
                Convert.ToInt32(width_B.Text),
                Convert.ToInt32(width_P.Text)
            };

            var ijudge = new int[] {
                Convert.ToInt32(1),
                Convert.ToInt32(chroma_suppress_en.Checked),
                Convert.ToInt32(1),
                Convert.ToInt32(Red_sup_en.Checked),
                Convert.ToInt32(1),
                Convert.ToInt32(1),
                Convert.ToInt32(1),
            };

            var ijudge1 = new int[] {
                Convert.ToInt32(color_enhance_en.Checked),
                Convert.ToInt32(Red_enh_en.Checked),
                Convert.ToInt32(chroma_suppress_en.Checked),
                Convert.ToInt32(Red_sup_en.Checked),
                Convert.ToInt32(Purple_enh_en.Checked),
                Convert.ToInt32(Green_enh_en.Checked),
                Convert.ToInt32(Blue_enh_en.Checked),
                Convert.ToInt32(color_enhance_max_man_en),
                Convert.ToInt32(Luma_sup_en.Checked),
                Convert.ToInt32(Sat_sup_en.Checked),
            };
            var para = new double[] {
                Convert.ToInt32(mem_color_enhance_max_man_r),
                Convert.ToInt32(mem_color_enhance_max_man_g),
                Convert.ToInt32(mem_color_enhance_max_man_b),
                Convert.ToInt32(mem_color_enhance_max_man_p),
                Convert.ToInt32(maxV_R.Text,16),
                Convert.ToInt32(maxV_G.Text,16),
                Convert.ToInt32(maxV_B.Text,16),
                Convert.ToInt32(maxV_P.Text,16),
                Convert.ToInt32(D_L.Text,16),
                Convert.ToInt32(D_S.Text,16),
                Convert.ToInt32(D_R.Text,16),
            };



            Task.Run(() => {
                WaitBeforeLogin = new DevExpress.Utils.WaitDialogForm("请稍候...", "正在加载CADJ应用系统");
                WaitBeforeLogin.StartPosition = FormStartPosition.CenterParent;
                Application.Run(WaitBeforeLogin);
            });



            try
            {
                MyData sd = new MyData();
                sd.data = new int[2];
                sd.cMessage = new IntPtr(2121);
                sd.bResult = false;

                if (IntPtr.Size == 8)
                {
                    //var a1 = JsonConvert.SerializeObject(irow);
                    //var b1 = JsonConvert.SerializeObject(boundary);
                    //var c1 = JsonConvert.SerializeObject(paraWidth);
                    //var d1 = JsonConvert.SerializeObject(ijudge);
                    CadjHelp.para_gen64(ref sd, savepath, readpath, irow, boundary, paraWidth, ijudge);
                    CadjHelp.colorzone64(ref sd, strpath, ijudge1, boundary, paraWidth, para);
                    if (!sd.bResult && !Marshal.PtrToStringAnsi(sd.cMessage).ToLower().Contains("succ"))
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("错误信息：" + Marshal.PtrToStringAnsi(sd.cMessage));
                    }
                }
                else {
                    CadjHelp.para_gen86(ref sd, savepath, readpath, irow, boundary, paraWidth, ijudge);
                    CadjHelp.colorzone86(ref sd, strpath, ijudge1, boundary, paraWidth, para);
                }
                var img = Image.FromFile(savepath);
                img.RotateFlip(RotateFlipType.Rotate90FlipNone);
                img_dst_in1.Image = img;
                var regList = Setting2Help.RegArrToPath(strpath);
                uint writeVal = regList.First(c => c.addr == 0x430d).value;
                SendNormalORRedlight("U_R", writeVal);
                writeVal = regList.First(c => c.addr == 0x430e).value;
                SendNormalORRedlight("V_R", writeVal);
                writeVal = regList.First(c => c.addr == 0x430f).value;
                SendNormalORRedlight("width_R", writeVal);
                writeVal = regList.First(c => c.addr == 0x4310).value;
                SendNormalORRedlight("slop_R", writeVal);
                writeVal = regList.First(c => c.addr == 0x4311).value;
                SendNormalORRedlight("shift_R", writeVal);

                writeVal = regList.First(c => c.addr == 0x431c).value;
                SendNormalORRedlight("U_G", writeVal);
                writeVal = regList.First(c => c.addr == 0x431d).value;
                SendNormalORRedlight("V_G", writeVal);
                writeVal = regList.First(c => c.addr == 0x431e).value;
                SendNormalORRedlight("width_G", writeVal);
                writeVal = regList.First(c => c.addr == 0x431f).value;
                SendNormalORRedlight("slop_G", writeVal);
                writeVal = regList.First(c => c.addr == 0x4320).value;
                SendNormalORRedlight("shift_G", writeVal);

                writeVal = regList.First(c => c.addr == 0x432b).value;
                SendNormalORRedlight("U_B", writeVal);
                writeVal = regList.First(c => c.addr == 0x432c).value;
                SendNormalORRedlight("V_B", writeVal);
                writeVal = regList.First(c => c.addr == 0x432d).value;
                SendNormalORRedlight("width_B", writeVal);
                writeVal = regList.First(c => c.addr == 0x432e).value;
                SendNormalORRedlight("slop_B", writeVal);
                writeVal = regList.First(c => c.addr == 0x432f).value;
                SendNormalORRedlight("shift_B", writeVal);

                writeVal = regList.First(c => c.addr == 0x433a).value;
                SendNormalORRedlight("U_P", writeVal);
                writeVal = regList.First(c => c.addr == 0x433b).value;
                SendNormalORRedlight("V_P", writeVal);
                writeVal = regList.First(c => c.addr == 0x433c).value;
                SendNormalORRedlight("width_P", writeVal);
                writeVal = regList.First(c => c.addr == 0x433d).value;
                SendNormalORRedlight("slop_P", writeVal);
                writeVal = regList.First(c => c.addr == 0x433e).value;
                SendNormalORRedlight("shift_P", writeVal);

                WaitBeforeLogin.Invoke((EventHandler)delegate { WaitBeforeLogin.Close(); });
                btn.Invoke((EventHandler)delegate { btn.Enabled = true; });
            }
            catch (Exception ex)
            {
                WaitBeforeLogin.Invoke((EventHandler)delegate { WaitBeforeLogin.Close(); });
                btn.Invoke((EventHandler)delegate { btn.Enabled = true; });
                DevExpress.XtraEditors.XtraMessageBox.Show("错误信息：" + ex.Message.ToString());
            }
        }

        private void simpleButton3_MouseEnter(object sender, EventArgs e)
        {
            isWrite = true;
        }

        private void simpleButton3_MouseLeave(object sender, EventArgs e)
        {
            isWrite = false;
        }

        void PackedColorEnhance(SimpleButton btn) {
            btn.Invoke((EventHandler)delegate { btn.Enabled = false; });
            var strpath = string.Format("{0}\\Lib\\xc_m\\{1}", Application.StartupPath, $"ColorEnhance_Out{DateTime.Now.ToString("ddHHmmss")}{System.IO.Path.GetFileName(cadjPath)}.txt");
            //boundary 坐标系
            var boundary = new double[4, 2] { { int.Parse(U_R.Text),int.Parse(V_R.Text) },
                { int.Parse(U_G.Text),int.Parse(V_G.Text) },
                {int.Parse(U_B.Text),int.Parse(V_B.Text) },
                { int.Parse(U_P.Text),int.Parse(V_P.Text) }
            };
            var paraWidth = new double[] {
                Convert.ToInt32(width_R.Text),
                Convert.ToInt32(width_G.Text),
                Convert.ToInt32(width_B.Text),
                Convert.ToInt32(width_P.Text)
            };
            var ijudge = new int[] {
                Convert.ToInt32(color_enhance_en.Checked),
                Convert.ToInt32(Red_enh_en.Checked),
                Convert.ToInt32(chroma_suppress_en.Checked),
                Convert.ToInt32(Red_sup_en.Checked),
                Convert.ToInt32(Purple_enh_en.Checked),
                Convert.ToInt32(Green_enh_en.Checked),
                Convert.ToInt32(Blue_enh_en.Checked),
                Convert.ToInt32(color_enhance_max_man_en),
                Convert.ToInt32(Luma_sup_en.Checked),
                Convert.ToInt32(Sat_sup_en.Checked),
            };
            var para = new double[] {
                Convert.ToInt32(mem_color_enhance_max_man_r),
                Convert.ToInt32(mem_color_enhance_max_man_g),
                Convert.ToInt32(mem_color_enhance_max_man_b),
                Convert.ToInt32(mem_color_enhance_max_man_p),
                Convert.ToInt32(maxV_R.Text,16),
                Convert.ToInt32(maxV_G.Text,16),
                Convert.ToInt32(maxV_B.Text,16),
                Convert.ToInt32(maxV_P.Text,16),
                Convert.ToInt32(D_L.Text,16),
                Convert.ToInt32(D_S.Text,16),
                Convert.ToInt32(D_R.Text,16),
                Convert.ToInt32(Q_K),
                Convert.ToInt32(y1_R.Text,16),
                Convert.ToInt32(y2_R.Text,16),
                Convert.ToInt32(y3_R.Text,16),
                Convert.ToInt32(y4_R.Text,16),

                Convert.ToInt32(y1_G.Text,16),
                Convert.ToInt32(y2_G.Text,16),
                Convert.ToInt32(y3_G.Text,16),
                Convert.ToInt32(y4_G.Text,16),

                Convert.ToInt32(y1_B.Text,16),
                Convert.ToInt32(y2_B.Text,16),
                Convert.ToInt32(y3_B.Text,16),
                Convert.ToInt32(y4_B.Text,16),

                Convert.ToInt32(y1_P.Text,16),
                Convert.ToInt32(y2_P.Text,16),
                Convert.ToInt32(y3_P.Text,16),
                Convert.ToInt32(y4_P.Text,16),
            };

            //Task.Run(() => {
            //    WaitBeforeLogin = new DevExpress.Utils.WaitDialogForm("请稍候...", "正在加载CADJ应用系统");
            //    WaitBeforeLogin.StartPosition = FormStartPosition.CenterParent;
            //    Application.Run(WaitBeforeLogin);
            //});
            try
            {
                MyData sd = new MyData();
                sd.data = new int[2];
                sd.cMessage = new IntPtr(2121);
                sd.bResult = false;

                if (IntPtr.Size == 8)
                {
                    CadjHelp.colorenhance64(ref sd, strpath, ijudge, boundary, paraWidth, para);
                    if (!sd.bResult && !Marshal.PtrToStringAnsi(sd.cMessage).ToLower().Contains("succ"))
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("错误信息：" + Marshal.PtrToStringAnsi(sd.cMessage));
                        return;
                    }
                }
                else
                {
                    CadjHelp.colorenhance86(ref sd, strpath, ijudge, boundary, paraWidth, para);
                }
                
                var regList = Setting2Help.RegArrToPath(strpath);
                uint writeVal = regList.First(c => c.addr == 0x4303).value;
                SendNormalORRedlight("maxV_R_h", writeVal);
                writeVal = regList.First(c => c.addr == 0x4304).value;
                SendNormalORRedlight("maxV_R_l", writeVal);
                writeVal = regList.First(c => c.addr == 0x4305).value;
                SendNormalORRedlight("y1_R", writeVal);
                writeVal = regList.First(c => c.addr == 0x4306).value;
                SendNormalORRedlight("y2_R", writeVal);
                writeVal = regList.First(c => c.addr == 0x4307).value;
                SendNormalORRedlight("y3_R", writeVal);
                writeVal = regList.First(c => c.addr == 0x4308).value;
                SendNormalORRedlight("y4_R", writeVal);
                writeVal = regList.First(c => c.addr == 0x4309).value;
                SendNormalORRedlight("ym1_R", writeVal);
                writeVal = regList.First(c => c.addr == 0x430a).value;
                SendNormalORRedlight("ym3_R", writeVal);
                writeVal = regList.First(c => c.addr == 0x430b).value;
                SendNormalORRedlight("ys1_R", writeVal);
                writeVal = regList.First(c => c.addr == 0x430c).value;
                SendNormalORRedlight("ys3_R", writeVal);

                writeVal = regList.First(c => c.addr == 0x4312).value;
                SetCADJRegister("maxV_G_h", writeVal);
                writeVal = regList.First(c => c.addr == 0x4313).value;
                SetCADJRegister("maxV_G_l", writeVal);
                writeVal = regList.First(c => c.addr == 0x4314).value;
                SetCADJRegister("y1_G", writeVal);
                writeVal = regList.First(c => c.addr == 0x4315).value;
                SetCADJRegister("y2_G", writeVal);
                writeVal = regList.First(c => c.addr == 0x4316).value;
                SetCADJRegister("y3_G", writeVal);
                writeVal = regList.First(c => c.addr == 0x4317).value;
                SetCADJRegister("y4_G", writeVal);
                writeVal = regList.First(c => c.addr == 0x4318).value;
                SetCADJRegister("ym1_G", writeVal);
                writeVal = regList.First(c => c.addr == 0x4319).value;
                SetCADJRegister("ym3_G", writeVal);
                writeVal = regList.First(c => c.addr == 0x431a).value;
                SetCADJRegister("ys1_G", writeVal);
                writeVal = regList.First(c => c.addr == 0x431b).value;
                SetCADJRegister("ys3_G", writeVal);

                writeVal = regList.First(c => c.addr == 0x4321).value;
                SetCADJRegister("maxV_B_h", writeVal);
                writeVal = regList.First(c => c.addr == 0x4322).value;
                SetCADJRegister("maxV_B_l", writeVal);
                writeVal = regList.First(c => c.addr == 0x4323).value;
                SetCADJRegister("y1_B", writeVal);
                writeVal = regList.First(c => c.addr == 0x4324).value;
                SetCADJRegister("y2_B", writeVal);
                writeVal = regList.First(c => c.addr == 0x4325).value;
                SetCADJRegister("y3_B", writeVal);
                writeVal = regList.First(c => c.addr == 0x4326).value;
                SetCADJRegister("y4_B", writeVal);
                writeVal = regList.First(c => c.addr == 0x4327).value;
                SetCADJRegister("ym1_B", writeVal);
                writeVal = regList.First(c => c.addr == 0x4328).value;
                SetCADJRegister("ym3_B", writeVal);
                writeVal = regList.First(c => c.addr == 0x4329).value;
                SetCADJRegister("ys1_B", writeVal);
                writeVal = regList.First(c => c.addr == 0x432a).value;
                SetCADJRegister("ys3_B", writeVal);

                writeVal = regList.First(c => c.addr == 0x4330).value;
                SetCADJRegister("maxV_P_h", writeVal);
                writeVal = regList.First(c => c.addr == 0x4331).value;
                SetCADJRegister("maxV_P_l", writeVal);
                writeVal = regList.First(c => c.addr == 0x4332).value;
                SetCADJRegister("y1_P", writeVal);
                writeVal = regList.First(c => c.addr == 0x4333).value;
                SetCADJRegister("y2_P", writeVal);
                writeVal = regList.First(c => c.addr == 0x4334).value;
                SetCADJRegister("y3_P", writeVal);
                writeVal = regList.First(c => c.addr == 0x4335).value;
                SetCADJRegister("y4_P", writeVal);
                writeVal = regList.First(c => c.addr == 0x4336).value;
                SetCADJRegister("ym1_P", writeVal);
                writeVal = regList.First(c => c.addr == 0x4337).value;
                SetCADJRegister("ym3_P", writeVal);
                writeVal = regList.First(c => c.addr == 0x4338).value;
                SetCADJRegister("ys1_P", writeVal);
                writeVal = regList.First(c => c.addr == 0x4339).value;
                SetCADJRegister("ys3_P", writeVal);

                //WaitBeforeLogin.Invoke((EventHandler)delegate { WaitBeforeLogin.Close(); });
                btn.Invoke((EventHandler)delegate { btn.Enabled = true; });
            }
            catch (Exception ex)
            {
                //WaitBeforeLogin.Invoke((EventHandler)delegate { WaitBeforeLogin.Close(); });
                btn.Invoke((EventHandler)delegate { btn.Enabled = true; });
                DevExpress.XtraEditors.XtraMessageBox.Show("错误信息：" + ex.Message.ToString());
            }

        }

        void PackedChromaSuppress(SimpleButton btn) {
            btn.Invoke((EventHandler)delegate { btn.Enabled = false; });
            var strpath = string.Format("{0}\\Lib\\xc_m\\{1}", Application.StartupPath, $"ChromaSuppress_Out{DateTime.Now.ToString("ddHHmmss")}{System.IO.Path.GetFileName(cadjPath)}.txt");
            //boundary 坐标系
            var boundary = new double[4, 2] { { int.Parse(U_R.Text),int.Parse(V_R.Text) },
                { int.Parse(U_G.Text),int.Parse(V_G.Text) },
                {int.Parse(U_B.Text),int.Parse(V_B.Text) },
                { int.Parse(U_P.Text),int.Parse(V_P.Text) }
            };
            var paraWidth = new double[] {
                Convert.ToInt32(width_R.Text),
                Convert.ToInt32(width_G.Text),
                Convert.ToInt32(width_B.Text),
                Convert.ToInt32(width_P.Text)
            };
            var ijudge = new int[] {
                Convert.ToInt32(color_enhance_en.Checked),
                Convert.ToInt32(Red_enh_en.Checked),
                Convert.ToInt32(chroma_suppress_en.Checked),
                Convert.ToInt32(Red_sup_en.Checked),
                Convert.ToInt32(Purple_enh_en.Checked),
                Convert.ToInt32(Green_enh_en.Checked),
                Convert.ToInt32(Blue_enh_en.Checked),
                Convert.ToInt32(color_enhance_max_man_en),
                Convert.ToInt32(Luma_sup_en.Checked),
                Convert.ToInt32(Sat_sup_en.Checked),
            };
            var para = new double[] {
                Convert.ToInt32(mem_color_enhance_max_man_r),
                Convert.ToInt32(mem_color_enhance_max_man_g),
                Convert.ToInt32(mem_color_enhance_max_man_b),
                Convert.ToInt32(mem_color_enhance_max_man_p),
                Convert.ToInt32(maxV_R.Text,16),
                Convert.ToInt32(maxV_G.Text,16),
                Convert.ToInt32(maxV_B.Text,16),
                Convert.ToInt32(maxV_P.Text,16),
                Convert.ToInt32(D_L.Text,16),
                Convert.ToInt32(D_S.Text,16),
                Convert.ToInt32(D_R.Text,16),
                Convert.ToInt32(y1.Text,16),
                Convert.ToInt32(y2.Text,16),
                Convert.ToInt32(y3.Text,16),
                Convert.ToInt32(y4.Text,16),
                Convert.ToInt32(s1.Text,16),
                Convert.ToInt32(s2.Text,16)
            };


            //Task.Run(() => {
            //    WaitBeforeLogin = new DevExpress.Utils.WaitDialogForm("请稍候...", "正在加载CADJ应用系统");
            //    WaitBeforeLogin.StartPosition = FormStartPosition.CenterParent;
            //    Application.Run(WaitBeforeLogin);
            //});



            try
            {
                MyData sd = new MyData();
                sd.data = new int[2];
                sd.cMessage = new IntPtr(2121);
                sd.bResult = false;

                if (IntPtr.Size == 8)
                {
                    CadjHelp.chromasuppress64(ref sd, strpath, ijudge, boundary, paraWidth, para);
                    if (!sd.bResult && !Marshal.PtrToStringAnsi(sd.cMessage).ToLower().Contains("succ"))
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("错误信息：" + Marshal.PtrToStringAnsi(sd.cMessage));
                    }
                }
                else
                {
                    CadjHelp.chromasuppress86(ref sd, strpath, ijudge, boundary, paraWidth, para);
                }
                
                var regList = Setting2Help.RegArrToPath(strpath);
                uint writeVal = regList.First(c => c.addr == 0x433f).value;
                SetCADJRegister("y1", writeVal);
                writeVal = regList.First(c => c.addr == 0x4340).value;
                SetCADJRegister("y2", writeVal);
                writeVal = regList.First(c => c.addr == 0x4341).value;
                SetCADJRegister("y3", writeVal);
                writeVal = regList.First(c => c.addr == 0x4342).value;
                SetCADJRegister("y4", writeVal);
                writeVal = regList.First(c => c.addr == 0x4343).value;
                SetCADJRegister("ym1", writeVal);
                writeVal = regList.First(c => c.addr == 0x4344).value;
                SetCADJRegister("ym3", writeVal);
                writeVal = regList.First(c => c.addr == 0x4345).value;
                SetCADJRegister("ys1", writeVal);
                writeVal = regList.First(c => c.addr == 0x4346).value;
                SetCADJRegister("ys3", writeVal);
                writeVal = regList.First(c => c.addr == 0x4347).value;
                SetCADJRegister("s1", writeVal);
                writeVal = regList.First(c => c.addr == 0x4348).value;
                SetCADJRegister("s2", writeVal);
                writeVal = regList.First(c => c.addr == 0x4349).value;
                SetCADJRegister("sm1", writeVal);
                writeVal = regList.First(c => c.addr == 0x434a).value;
                SetCADJRegister("ss1", writeVal);
                writeVal = regList.First(c => c.addr == 0x434b).value;
                SetCADJRegister("D_L", writeVal);
                writeVal = regList.First(c => c.addr == 0x434c).value;
                SetCADJRegister("D_S", writeVal);
                writeVal = regList.First(c => c.addr == 0x434d).value;
                SendNormalORRedlight("D_R", writeVal);

                //WaitBeforeLogin.Invoke((EventHandler)delegate { WaitBeforeLogin.Close(); });
                btn.Invoke((EventHandler)delegate { btn.Enabled = true; });
            }
            catch (Exception ex)
            {
                //WaitBeforeLogin.Invoke((EventHandler)delegate { WaitBeforeLogin.Close(); });
                btn.Invoke((EventHandler)delegate { btn.Enabled = true; });
                DevExpress.XtraEditors.XtraMessageBox.Show("错误信息：" + ex.Message.ToString());
            }
        }
        //void PackedCadjData
        string PositiveNegativeConversion(uint num,bool isbool = true) {
            if (isbool)
            {
                if (num >= 128)
                {
                    return unAbs(int.Parse(((int)(num - 256)).ToString())).ToString();
                }
                else
                {
                    return unAbs(int.Parse(num.ToString())).ToString();
                }
            }
            else {
                if (num >= 128)
                {
                    return ((int)(num - 256)).ToString();
                }
                else
                {
                    return num.ToString();
                }
            }
            
            //if ((num >> 7 & 0x01) == 1)
            //{
            //    return ((256 - Math.Abs(Convert.ToInt32(num.ToString("X2"), 16))) * -1).ToString();
            //}
            //else {
            //    return Math.Abs(Convert.ToInt32(num.ToString("X2"), 16)).ToString();
            //}
        }


        public XChip_Lite_CADJ_C()
        {
            InitializeComponent();
        }

        public XChip_Lite_CADJ_C(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            sPortTemp = _sPortTemp;
            aBll = _aBll;
            XChipCadj_c = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "CADJ" || c.Classify == "Common"));
            InitializeComponent();
        }
        /// <summary>
        /// 加载图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton5_Click(object sender, EventArgs e)
        {
            
            OpenFileDialog dlgOpen = new OpenFileDialog();
            dlgOpen.Filter = "All Image Files(*.*)|*.*";
            //cadjPath = string.Empty;
            if (dlgOpen.ShowDialog() == DialogResult.OK)
            {
                cadjPath = string.Empty;
                if (dlgOpen.FileName == "") return;
                var strFilename = dlgOpen.FileName;
                Image imgWine = Image.FromFile(strFilename);
                if (imgWine.PixelFormat != PixelFormat.Format24bppRgb)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("只支持24位宽的bmp");
                    return;
                }
                if (imgWine.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp))
                {
                    cadjPath = strFilename;
                }
                else {
                    //string.Format("{0}\\Lib\\xc_m\\{1}", Application.StartupPath, $"Cadj_Out{DateTime.Now.ToString("ddHHmmss")}{System.IO.Path.GetFileName(cadjPath)}.bmp");
                    cadjPath = $"{Application.StartupPath}\\Lib\\xc_m\\{Path.GetFileNameWithoutExtension(strFilename)}.bmp";
                    using (Bitmap bmp = new Bitmap(imgWine.Width, imgWine.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
                    {
                        System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                        ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Bmp);
                        EncoderParameters myEncoderParameters = new EncoderParameters(1);
                        EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 100L);
                        myEncoderParameters.Param[0] = myEncoderParameter;
                        bmp.SetResolution(imgWine.HorizontalResolution, imgWine.VerticalResolution);
                        using (var g = Graphics.FromImage(bmp))
                        {
                            g.Clear(Color.White);
                            g.DrawImageUnscaled(imgWine, 0, 0);
                        }
                        bmp.Save(cadjPath, jpgEncoder, myEncoderParameters);
                   }
                }
               
              
               
                
               

                //Graphics g = Graphics.FromImage(bmp);
                //g.DrawImage(imgWine, 0, 0, imgWine.Width, imgWine.Height);

                XChip_ImgShow cadjF = new XChip_ImgShow(cadjPath, true);
                cadjF.SendCadjImage += CadjF_SendCadjImage;
                cadjF.Show();
            }
        }

        private ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }

            return null;
        }
        private void CadjF_SendCadjImage(int x, int y, int w, int h)
        {
            cadjX = x;
            cadjY = y;
            cadjW = w;
            cadjH = h;
            //不显示坐标系
            //region_click.Invoke((EventHandler)(delegate {
            //    region_click.Text = $"region_click[{x} {y};{x + w} {y};{x + w} {y + h};{x} {y + h};]";
            //}));
        }

        private Control[] Controls_Find(string type)
        {
            //var t =   this.Controls.Find(type, true);
            //Control[] listc = new Control[100];
            List<Control> listc = new List<Control>();
            System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            for (int i = 0; i < fieldInfo.Length; i++)
            {
                if (fieldInfo[i].Name.ToLower() == type.ToLower() && !listc.Exists(c => c.Name.ToLower() == (fieldInfo[i].Name.ToLower())))
                {
                    listc.AddRange(this.Controls.Find(fieldInfo[i].Name, true));
                    //break;
                }
            }
            return listc.ToArray();
        }

    }
}
